<?php

namespace common\models\business;

use Yii;

/**
 * This is the model class for table "business_customer".
 *
 * @property string $id
 * @property integer $cateid
 * @property string $name
 * @property string $personA
 * @property string $personB
 * @property string $connect_tel
 * @property string $connect_address
 * @property string $status
 */
class BusinessCustomer extends \yii\db\ActiveRecord
{


    const STATUS_NOMAL = 0;
    const STATUS_STOP = 1;
    public static $statues = [
        self::STATUS_NOMAL => '正常',
        self::STATUS_STOP => '终止合作'
    ];


    //主要用于日志记录
    public $uselog = [
        'tabcomment' => '大客户',      //用于修改了什么的显示
        'mainfield' => 'name',      //主要的显示标题的字段
        'picturefield' => [],        //图片字段
        'timefield' => [],       //时间字段
        'unsetfiled' =>[],      //不需要记录的字段
    ];



    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'business_customer';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name','number'],'required'],
            [['cateid','operator'], 'integer'],
            [['name', 'personA', 'personB', 'connect_tel', 'connect_address', 'status'], 'string', 'max' => 255],
            [['number'], 'string', 'max' => 50],
            ['createtime','integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'cateid' => '分类',
            'name' => '客户名称',
            'personA' => '客户联系人',
            'personB' => '牧心负责人',
            'connect_tel' => '联系电话',
            'connect_address' => '客户地址',
            'createtime' => '创建时间',
            'status' => '状态',
            'operator' => '操作者',
            'number' => '客户编码',
        ];
    }

    public function beforeSave($insert)
    {
        if($this->isNewRecord){
            $this->createtime = time();
            $this->operator = Yii::$app->user->id;      //谁添加的谁就是操作者
        }
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }


    /**
     * @return \yii\db\ActiveQuery
     * 获取大客户分类
     */
    public function getCate()
    {
        return $this->hasOne(BusinessCustomerCategory::className(),['id'=>'cateid']);
    }



    /**
     * @return mixed
     *
     */
    public function getAddonField()
    {
        if($this->cate){
            return $this->cate->hasMany(BusinessCustomerField::className(),['cateid'=>'id']);
        }
        return false;
    }

    /**
     * @param $customerid
     * @param $fieldid
     * @return mixed
     * 获取附加字段的值
     */
    public static function fieldValue($customerid,$fieldid)
    {
        $value = BusinessCustomerFieldvalue::find()->select('value')->where('customerid=:id and fieldid=:fid',[':id'=>$customerid,':fid'=>$fieldid])->asArray()->one();
        return $value['value'];
    }


}
